<template>
  <div class="rule-table">
    <n-data-table
      :columns="columns"
      :data="rules"
      :loading="loading"
      :pagination="paginationConfig"
      :row-key="(row: Rule) => row.id"
      size="small"
      striped
    />
  </div>
</template>

<script setup lang="ts">
import { h, computed } from 'vue';
import { type DataTableColumns, type PaginationProps, NSwitch, NButton, NIcon, useDialog } from 'naive-ui';
import EditOutline from '@vicons/ionicons5/Create';
import DeleteOutline from '@vicons/ionicons5/Trash';
import PlayOutline from '@vicons/ionicons5/Play';
import { formatTimestamp } from '../../utils/format';
import type { Rule } from '../../types';

const props = defineProps<{
  rules: Rule[];
  loading: boolean;
}>();

const emit = defineEmits<{
  edit: [rule: Rule];
  delete: [ruleId: string];
  toggle: [ruleId: string, enabled: boolean];
}>();

const dialog = useDialog();

// 分页配置
const paginationConfig: PaginationProps = {
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
  prefix: ({ itemCount }) => `共 ${itemCount} 条`
};

// 表格列定义
const columns: DataTableColumns<Rule> = [
  {
    title: '规则名称',
    key: 'name',
    minWidth: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '状态',
    key: 'enabled',
    width: 100,
    render: (row) => {
      return h(NSwitch, {
        value: row.enabled,
        onUpdateValue: (value: boolean) => emit('toggle', row.id, value)
      });
    }
  },
  {
    title: '条件数量',
    key: 'conditions',
    width: 100,
    render: (row) => row.conditions.length
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 160,
    render: (row) => formatTimestamp(row.createdAt)
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    width: 160,
    render: (row) => formatTimestamp(row.updatedAt)
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render: (row) => {
      return h('div', { style: 'display: flex; gap: 8px;' }, [
                 h(NButton, {
           size: 'small',
           type: 'primary',
           quaternary: true,
           onClick: () => {
             emit('edit', row);
           }
         }, {
           icon: () => h(NIcon, { component: EditOutline })
         }),
        h(NButton, {
          size: 'small',
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(row)
        }, {
          icon: () => h(NIcon, { component: DeleteOutline })
        })
      ]);
    }
  }
];

// 删除确认
const handleDelete = (rule: Rule) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除规则 "${rule.name}" 吗？此操作不可撤销。`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      emit('delete', rule.id);
    }
  });
};
</script>

<style scoped>
.rule-table {
  flex: 1;
}
</style> 